<template>
  <div class="login-page">
    <el-form ref="loginForm" :model="loginForm" :rules="rules" class="login-form" label-position="left">
      <h3 class="title">小金宝专属工具系统</h3>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" placeholder="请公主输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
            :type="passwordInputType"
            v-model="loginForm.password"
            placeholder="请公主输入密码"
            @focus="handlePasswordFocus"
            @blur="handlePasswordBlur"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')">公主请登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      passwordInputType: 'text',
      rules: {
        username: [{ required: true, message: '公主请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '公主请输入密码', trigger: 'blur' }]
      }
    };
  },
  created() {
    console.log('当前路径:', this.$route.path);
  },
  methods: {
    handlePasswordFocus() {
      this.loginForm.password = '';
      this.passwordInputType = 'password';
    },
    handlePasswordBlur() {
      if (!this.loginForm.password) {
        this.passwordInputType = 'text';
      }
    },
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const response = await axios.post('/login',
                JSON.stringify({
                  username: this.loginForm.username,
                  password: this.loginForm.password
                }),
                {
                  headers: {
                    'Content-Type': 'application/json'
                  }
                }
            );

            if (response.data.code === 200) {
              console.log('登录成功');
              // 将用户名存储在localStorage中
              localStorage.setItem('username', this.loginForm.username);
              // 设置默认的请求头，包含用户名
              axios.defaults.headers.common['username'] = this.loginForm.username;
              const currentPath = this.$route.path;
              if (currentPath !== '/dashboard') {
                await this.$router.push({ name: 'DashboardPage' });
              } else {
                console.log('已经在 /dashboard 页面，无需导航');
              }
            } else {
              this.$message.error('用户名或密码错误');
            }
          } catch (error) {
            console.error('登录错误:', error);
            this.$message.error('用户名或密码错误');
          }
        } else {
          console.log('验证失败');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  overflow-y: scroll;
  scrollbar-width: none;
  -ms-overflow-style: none;
  background-image: url(../assets/pdx.png);
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  background-color: #f5f7fa;
}

.login-page::-webkit-scrollbar {
  display: none;
}

.login-form {
  width: 300px;
  padding: 30px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 50px;
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: purple;
}

.error-message {
  color: black;
}

.login-image {
  display: block;
  margin: 0 auto 20px;
  max-width: 100px;
}
</style>
